<?php
/*
 * bz漫画 请求方式：GET 参数： count=count&page=page 参数c表示请求的条数；参数p表示请求第几页
 */
require_once 'file_php.php';
require_once 'JG_Cache.php';

$kExpiration = 5 * 60;
$kPage = "page";
$kCountKeyword = "count";
$kType = "type";

$kDefaultType ="latest";
$kDefaultFormatServerUrl = "http://api.bao.fm/groups/19/latest/page/%s//%s.app";
$kDefaultCount = 20;
$kDefaultPage = 1;

$kServerFormatUrls = array(
        "hot" => "http://api.bao.fm/groups/19/recenthot/page/%s//%s.app",
        $kDefaultType => $kDefaultFormatServerUrl
);


$kDataInputTag = "articles";
$kDataOutputTag = "data";

$kFilterKeys = array(
        "title" => "description",
        "pictures" => "large_url"
);

set_time_limit(0);
$page = $_GET[$kPage];
$page = (false == $page) ? $kDefaultPage : $page;

$count = $_GET[$kCountKeyword];
$count = (false == $count) ? $kDefaultCount : $count;

$tag = $_GET[$kType];
$tag = (false == $tag) ? $kDefaultType : $tag;

$serverUrl = $kServerFormatUrls[$tag];
$serverFormatUrl = (false==$tag)?$kDefaultFormatServerUrl:$serverUrl;

$reqUrl = sprintf($serverFormatUrl, $page, $count);

// get cache data
$cache = new JG_Cache('cache'); // Make sure it exists and is writeable
$data = $cache->get($reqUrl, $kExpiration);

if ($data === false) {
    $data = file_php::getRemoteFile($reqUrl);
    
    $data = json_decode($data, true);
    // remove junk data
    $respArray = $data[$kDataInputTag];
    $rearrangeArray = array();
    $current = array();
    foreach ($respArray as $itemArray) {
        foreach ($itemArray as $item => $value) {
            // echo $item . ":" . $value . "<br/>";
            $filterValue = $kFilterKeys[$item];
            if (false != $filterValue) {
                $current[$filterValue] = $value;
                // echo $filterValue . "filterValue:" . $value . "<br/>";
            }
        }
        
        $rearrangeArray[] = $current;
    }
    
    // save to cache
    $data = json_encode(
            array(
                    $kDataOutputTag => $rearrangeArray
            ));
    
    $cache->set($reqUrl, $data);
}
echo $data;
?>